#include <semaphore.h>
sem_t mutex_alice;
sem_t mutex_john;
sem_t mutex_mary;
sem_t mutex_tom;

void mic_init ()
{
   if ( sem_init ( &mutex_alice, 0, 1) == -1 )
   {
      printf ( "alice semaphore init" );
   }
   if ( sem_init ( &mutex_john, 0, 0) == -1 )
   {
      printf ( "john semaphore init" );
   }
   if ( sem_init ( &mutex_mary, 0, 0) == -1 )
   {
      printf ( "mary semaphore init" );
   }
   if ( sem_init ( &mutex_tom, 0, 0) == -1 )
   {
      printf ( "tom semaphore init" );
   }
}

void mic_request (void *ptr)
{
   char *filename = (char *) ptr;
   if ( !strcmp ( filename, "Alice" ))
   {
      sem_wait ( &mutex_alice );
   }
   else if ( !strcmp ( filename, "John" ))
   {
      sem_wait ( &mutex_john );
   }
   else if ( !strcmp ( filename, "Mary" ))
   {
      sem_wait ( &mutex_mary );
   }
   else /* Assume Tom */
   {
      sem_wait ( &mutex_tom );
   }
}

void mic_relinquish (void *ptr)
{
   char *filename = (char *) ptr;
   if ( !strcmp ( filename, "Alice" ))
   {
      sem_post ( &mutex_john );
   }
   else if ( !strcmp ( filename, "John" ))
   {
      sem_post ( &mutex_mary );
   }
   else if ( !strcmp ( filename, "Mary" ))
   {
      sem_post ( &mutex_tom );
   }
   else /* Assume Tom*/
   {
      sem_post ( &mutex_alice );
   }
}
